package com.timothy.repo;

/**
 * Created by qtang on 7/2/13.
 */
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.ListActivity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.markupartist.android.widget.PullToRefreshListView;
import com.sina.stock.data.SinaStockClient;
import com.sina.stock.data.SinaStockInfo;
import com.timothy.repo.adapter.RepoAdaptor;
import com.timothy.repo.bean.Repo;
import com.timothy.repo.data.ParseXML;
import com.timothy.repo.util.NetWorkUtil;

public class RepoList extends ListActivity {
	 public static final String LOG_TAG = "RepoRefreshList";

	    Context mContext;
	    RepoAdaptor adaptor ;

	    /** Called when the activity is first created. */
	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.pull_to_refresh);

	        mContext = getApplicationContext();
	        

	        // Set a listener to be invoked when the list should be refreshed.
	        ((PullToRefreshListView) getListView()).setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() {
	            @Override
	            public void onRefresh() {
	                // Do work to refresh the list here.
	                new GetDataTask().execute();
	            }
	        });
	        
	        if(NetWorkUtil.isNetworkAvailable(mContext)){
	        	mClient = SinaStockClient.getInstance();
	        	new GetDataTask().execute();
	        }else{
	        	Toast.makeText(mContext, "Your network is not available!", Toast.LENGTH_LONG).show();
	        }

	        
	    }

	    private class GetDataTask extends AsyncTask<Void, Void, String[]> {

	        @Override
	        protected String[] doInBackground(Void... params) {
	            // Simulates a background job.
	            try {
	                Thread.sleep(2000);
	                loadData();
	            } catch (InterruptedException e) {
	            }
	            return null;
	        }

	        @Override
	        protected void onPostExecute(String[] result) {
	            super.onPostExecute(result);

	            adaptor = new RepoAdaptor(mContext, repoValueList);
	            setListAdapter(adaptor);
	            // Call onRefreshComplete when the list has been refreshed.
	            ((PullToRefreshListView) getListView()).onRefreshComplete();
	        }
	    }

	    SinaStockClient mClient;
	    List<String> codeList;
	    List<Repo> repoList;
	    List<Repo> repoValueList;

	    public void loadData(){
	        codeList = ParseXML.getRepoCodeList(mContext);
	        Map<String,Double> codeValueMap = null; //code&info Map
	        try {
	            //获取证券代码和信息（key:代码 Value 信息）
	            String[] array = new String[codeList.size()];
	            codeList.toArray(array); // fill the array
	            codeValueMap = mClient.getStockPrice(array);

	            repoValueList = new ArrayList<Repo>();
	            repoList = ParseXML.getRepoList(mContext);
	            for (Repo repo : repoList) {
	                String code= repo.getCode();
	                repo.setPrice(codeValueMap.get(code));
	                repoValueList.add(repo);
	            }
	        } catch (IOException e) {
	            Log.e(LOG_TAG, e.getMessage());
	        } catch (SinaStockInfo.ParseStockInfoException e) {
	            Log.e(LOG_TAG, e.getMessage());
	        }
	    }

	    public String reposNeedNotify(List<Repo> repoValueList){
	        StringBuffer sb = new StringBuffer();
	        for (Repo repo : repoValueList) {
	            if(repo.getPrice() >= 4){
	                sb.append( (sb.length()>0) ? (","+repo.getName()): repo.getName());
	            }
	        }
	        return sb.toString();
	    }

}
